package com.atguigu.order.orders.config;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class GuliFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                //我们需要重写这个apply方法
                //获取浏览器带给我们的老请求--我们使用上下文对象来获取
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (requestAttributes != null) {
                   //可以拿到请求对象
                    HttpServletRequest request = requestAttributes.getRequest();
                    if(request!=null){
                        String cookie = request.getHeader("Cookie");
                        //将老请求的cookie赋值给新请求
                        requestTemplate.header("Cookie",cookie);
                    }
                }
            }
        };

    }
}
